package net.adst.util;

import net.adst.beans.NaemTec;
import net.adst.beans.OurTecInf;
import net.adst.beans.OurTecRow;
import net.adst.resources.Constants;
import net.adst.resources.VariableNames;
import net.adst.ui.mainframe.tabs.ourTab.TecNamesPanel;
import org.apache.poi.hssf.extractor.ExcelExtractor;
import org.apache.poi.hssf.record.crypto.Biff8EncryptionKey;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import javax.swing.*;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.TreeSet;

/**
 * Created with IntelliJ IDEA.
 * User: alekseipot
 * Date: 09.11.12
 * Time: 3:29
 * To change this template use File | Settings | File Templates.
 */
public class MainDataBuilder {


    public static void buildData() {
        try {

            File file = new File(VariableNames.PATH_TO_BD);
            InputStream in = new FileInputStream(file);
            // Внимание InputStream будет закрыт
            // Если нужно не закрывающий см. JavaDoc по POIFSFileSystem :  http://goo.gl/1Auu7
            Biff8EncryptionKey.setCurrentUserPassword("adst-7777777");
            HSSFWorkbook wb = null;
            wb = new HSSFWorkbook(in);
            ExcelExtractor extractor = new ExcelExtractor(wb);
            extractor.setFormulasNotResults(true); // Считать формулы
            buildNaemTec(wb.getSheetAt(0));
            buildOurTecInfo();
            buildOurTec(wb);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }


    private static void buildNaemTec(HSSFSheet sheet) {
        ArrayList<NaemTec> naemTecs = new ArrayList<NaemTec>();
        TreeSet<String> tecModelNames = new TreeSet<String>();
        TreeSet<String> managerNames = new TreeSet<String>();
        TreeSet<String> customerNames = new TreeSet<String>();
        TreeSet<String> performerList = new TreeSet<String>();
        TreeSet<String> objectList = new TreeSet<String>();
        for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
            if (sheet.getRow(i) != null && MyUtils.isDate(sheet.getRow(i).getCell(0))) {
                NaemTec tec = new NaemTec(sheet.getRow(i));
                if (!tec.isEmpty()) {
                    naemTecs.add(tec);
                    tecModelNames.add(tec.getTecName());
                    managerNames.add(tec.getManagerName());
                    customerNames.add(tec.getCustomer());
                    performerList.add(tec.getPerformer());
                    objectList.add(tec.getObjectName());
                }
            }
        }
        DataManager.setObject(VariableNames.TEC_NAEM_ALL, naemTecs);

        WiderDropDownCombo tecNameCombo = (WiderDropDownCombo) DataManager.getObject(VariableNames.UI_NAEM_TECNAMECOMBO);
        ArrayList<String> tecNameList = new ArrayList<String>();
        ActionListener[] tecNameListeners = tecNameCombo.getActionListeners();
        for (ActionListener listener : tecNameListeners) {
            tecNameCombo.removeActionListener(listener);
        }
        tecNameCombo.setWidestLengh(tecModelNames);
        DefaultComboBoxModel namesTecModel = (DefaultComboBoxModel) DataManager.getObject(VariableNames.UI_NAEM_TECNAMECOMBO_MODEL);
        String tecNameCurrent = null;
        if (namesTecModel.getSelectedItem() != null) {
            tecNameCurrent = namesTecModel.getSelectedItem().toString();
        }
        namesTecModel.removeAllElements();
        namesTecModel.addElement(Constants.ALL_TEC);
        for (String tecModelName : tecModelNames) {
            namesTecModel.addElement(tecModelName);
            tecNameList.add(tecModelName);
        }
        if (tecNameCurrent != null && tecModelNames.contains(tecNameCurrent)) {
            namesTecModel.setSelectedItem(tecNameCurrent);
        }
        DataManager.setObject(VariableNames.TEC_NAEM_NAME_LIST, tecNameList);
        for (ActionListener listener : tecNameListeners) {
            tecNameCombo.addActionListener(listener);
        }

        WiderDropDownCombo managerCombo = (WiderDropDownCombo) DataManager.getObject(VariableNames.UI_NAEM_MANAGERCOMBO);
        ActionListener[] managerListeners = managerCombo.getActionListeners();
        ArrayList<String> managerList = new ArrayList<String>();
        for (ActionListener listener : managerListeners) {
            managerCombo.removeActionListener(listener);
        }
        managerCombo.setWidestLengh(managerNames);
        DefaultComboBoxModel managerModel = (DefaultComboBoxModel) DataManager.getObject(VariableNames.UI_NAEM_MANAGERCOMBO_MODEL);
        String managerCurrent = null;
        if (managerModel.getSelectedItem() != null) {
            managerCurrent = managerModel.getSelectedItem().toString();
        }
        managerModel.removeAllElements();
        managerModel.addElement(Constants.ALL_MANAGERS);
        for (String managerName : managerNames) {
            managerModel.addElement(managerName);
            managerList.add(managerName);
        }
        if (managerCurrent != null && managerNames.contains(managerCurrent)) {
            managerModel.setSelectedItem(managerCurrent);
        }
        DataManager.setObject(VariableNames.NAEM_MENAGER_LIST, managerList);
        for (ActionListener listener : managerListeners) {
            managerCombo.addActionListener(listener);
        }

        WiderDropDownCombo customerCombo = (WiderDropDownCombo) DataManager.getObject(VariableNames.UI_NAEM_CUSTOMERCOMBO);
        ActionListener[] customerListeners = customerCombo.getActionListeners();
        for (ActionListener listener : customerListeners) {
            customerCombo.removeActionListener(listener);
        }
        customerCombo.setWidestLengh(customerNames);
        DefaultComboBoxModel customerModel = (DefaultComboBoxModel) DataManager.getObject(VariableNames.UI_NAEM_CUSTOMERCOMBO_MODEL);
        String currentCustomer = null;
        if (customerModel.getSelectedItem() != null) {
            currentCustomer = customerModel.getSelectedItem().toString();
        }
        customerModel.removeAllElements();
        ArrayList<String> customerList = new ArrayList<String>();
        customerModel.addElement(Constants.ALL_CUSTOMERS);
        for (String customerName : customerNames) {
            customerModel.addElement(customerName);
            customerList.add(customerName);
        }
        if (currentCustomer != null && customerNames.contains(currentCustomer)) {
            customerModel.setSelectedItem(currentCustomer);
        }
        for (ActionListener listener : customerListeners) {
            customerCombo.addActionListener(listener);
        }

        WiderDropDownCombo performerCombo = (WiderDropDownCombo) DataManager.getObject(VariableNames.UI_NAEM_PERFORMERCOMBO);
        ActionListener[] performerListeners = customerCombo.getActionListeners();
        for (ActionListener listener : performerListeners) {
            performerCombo.removeActionListener(listener);
        }
        performerCombo.setWidestLengh(performerList);
        DefaultComboBoxModel performerModel = (DefaultComboBoxModel) DataManager.getObject(VariableNames.UI_NAEM_PERFORMERCOMBO_MODEL);
        String performerCurrent = null;
        if (performerModel.getSelectedItem() != null) {
            performerCurrent = performerModel.getSelectedItem().toString();
        }
        performerModel.removeAllElements();
        performerModel.addElement(Constants.ALL_PERFORMERS);
        for (String performerName : performerList) {
            performerModel.addElement(performerName);
        }
        if (performerCurrent != null && performerList.contains(performerCurrent)) {
            performerModel.setSelectedItem(performerCurrent);
        }
        for (ActionListener listener : performerListeners) {
            performerCombo.addActionListener(listener);
        }


        DataManager.setObject(VariableNames.TEC_NAEM_TEC_NAME_LIST, tecModelNames);
        DataManager.setObject(VariableNames.TEC_NAEM_CUSTOMER_LIST, customerList);
        DataManager.setObject(VariableNames.TEC_NAEM_PERFORMER_LIST, performerList);
        DataManager.setObject(VariableNames.TEC_NAEM_OBJECT_LIST, objectList);
    }

    public static void buildOurTecInfo() {
        try {
            File file = new File(VariableNames.PATH_TO_INFO);
            InputStream in = new FileInputStream(file);
            HSSFWorkbook wb = new HSSFWorkbook(in);
            ExcelExtractor extractor = new ExcelExtractor(wb);
            extractor.setFormulasNotResults(false); // Считать формулы
            HSSFSheet sheet = wb.getSheet("техника");
            for (int i = 0; i < 20; i++) {
                if (sheet.getRow(0).getCell(i) != null) {
                    if (sheet.getRow(0).getCell(i).toString().equals("дизель цена")) {
                        DataManager.setObject(VariableNames.TOPLIVO_COST, sheet.getRow(0).getCell(i + 1).toString());
                        ((JTextField) DataManager.getObject(VariableNames.UI_TOPLIVO_FIELD)).setText(sheet.getRow(0).getCell(i + 1).toString());
                        break;
                    }
                }
            }
            ArrayList<OurTecInf> ourTecInf = new ArrayList<OurTecInf>();
            for (int i = 1; i < sheet.getLastRowNum() + 1; i++) {
                if (sheet.getRow(i) != null) {
                    OurTecInf tecInf = new OurTecInf(sheet.getRow(i));
                    ourTecInf.add(tecInf);
                }
            }

            DataManager.setObject(VariableNames.TEC_OUR_INFO, ourTecInf);
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }

    }


    private static void buildOurTec(HSSFWorkbook wb) {
        ArrayList<OurTecRow> OurTec = new ArrayList<OurTecRow>();
        TreeSet<String> tecModelNames = new TreeSet<String>();
        TreeSet<String> surnames = new TreeSet<String>();
        TreeSet<String> customerNames = new TreeSet<String>();
        TreeSet<String> objectNames = new TreeSet<String>();
        for (int sh = 1; sh < wb.getNumberOfSheets(); sh++) {
//        for (int sh = 1; sh < 2; sh++) {
            HSSFSheet sheet = wb.getSheetAt(sh);
            for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
                if (sheet.getRow(i) != null && MyUtils.isDate(sheet.getRow(i).getCell(0))) {
                    OurTecRow tec = new OurTecRow(sheet.getRow(i), sheet.getSheetName());
                    if (!tec.isEmpty()) {
                        OurTec.add(tec);
                        surnames.add(tec.getSureName());
                        customerNames.add(tec.getCustomer());
                        objectNames.add(tec.getObjectName());
                    }
                }
            }
            tecModelNames.add(sheet.getSheetName());
        }
        DataManager.setObject(VariableNames.TEC_OUR_CUSTOMER_LIST, customerNames);
        DataManager.setObject(VariableNames.TEC_OUR_OBJECT_LIST, objectNames);
        DataManager.setObject(VariableNames.TEC_OUR_ALL, OurTec);

        WiderDropDownCombo tecNameCombo = (WiderDropDownCombo) DataManager.getObject(VariableNames.UI_OUR_TECNAMECOMBO);
        ArrayList<String> tecNameList = new ArrayList<String>();
        ActionListener[] tecNameListeners = tecNameCombo.getActionListeners();
        for (ActionListener listener : tecNameListeners) {
            tecNameCombo.removeActionListener(listener);
        }
        tecNameCombo.setWidestLengh(tecModelNames);
        DefaultComboBoxModel namesTecModel = (DefaultComboBoxModel) DataManager.getObject(VariableNames.UI_OUR_TECNAMECOMBO_MODEL);
        String currentTecName = null;
        if (namesTecModel.getSelectedItem() != null) {
            currentTecName = namesTecModel.getSelectedItem().toString();
        }
        namesTecModel.removeAllElements();
        namesTecModel.addElement(Constants.ALL_TEC);
        for (String tecModelName : tecModelNames) {
            namesTecModel.addElement(tecModelName);
            tecNameList.add(tecModelName);
        }
        if (currentTecName != null && tecModelNames.contains(currentTecName)) {
            namesTecModel.setSelectedItem(currentTecName);
        }
        DataManager.setObject(VariableNames.TEC_OUR_NAME_LIST, tecNameList);
        for (ActionListener listener : tecNameListeners) {
            tecNameCombo.addActionListener(listener);
        }

        WiderDropDownCombo surnameCombo = (WiderDropDownCombo) DataManager.getObject(VariableNames.UI_OUR_SURNAMECOMBO);
        ActionListener[] managerListeners = surnameCombo.getActionListeners();
        ArrayList<String> surnameList = new ArrayList<String>();
        for (ActionListener listener : managerListeners) {
            surnameCombo.removeActionListener(listener);
        }
        surnameCombo.setWidestLengh(surnames);
        DefaultComboBoxModel surnameModel = (DefaultComboBoxModel) DataManager.getObject(VariableNames.UI_OUR_SURNAMECOMBO_MODEL);
        String currentSurname = null;
        if (surnameModel.getSelectedItem() != null) {
            currentSurname = surnameModel.getSelectedItem().toString();
        }
        surnameModel.removeAllElements();
        surnameModel.addElement(Constants.ALL_SURNAME);
        for (String surname : surnames) {
            surnameModel.addElement(surname);
            surnameList.add(surname);
        }
        if (currentSurname != null && surnames.contains(currentSurname)) {
            surnameModel.setSelectedItem(currentSurname);
        }
        DataManager.setObject(VariableNames.OUR_SURNAME_LIST, surnameList);
        for (ActionListener listener : managerListeners) {
            surnameCombo.addActionListener(listener);
        }

        WiderDropDownCombo customerCombo = (WiderDropDownCombo) DataManager.getObject(VariableNames.UI_OUR_CUSTOMERCOMBO);
        ActionListener[] customerListeners = customerCombo.getActionListeners();
        for (ActionListener listener : customerListeners) {
            customerCombo.removeActionListener(listener);
        }
        customerCombo.setWidestLengh(customerNames);
        DefaultComboBoxModel customerModel = (DefaultComboBoxModel) DataManager.getObject(VariableNames.UI_OUR_CUSTOMERCOMBO_MODEL);
        String currentCustomer = null;
        if (customerModel.getSelectedItem() != null) {
            currentCustomer = customerModel.getSelectedItem().toString();
        }
        customerModel.removeAllElements();
        customerModel.addElement(Constants.ALL_CUSTOMERS);
        for (String customerName : customerNames) {
            customerModel.addElement(customerName);
        }
        if (currentCustomer != null && customerNames.contains(currentCustomer)) {
            customerModel.setSelectedItem(currentCustomer);
        }

        for (ActionListener listener : customerListeners) {
            customerCombo.addActionListener(listener);
        }
        TecNamesPanel.setNames(tecModelNames);
    }
}
